package com.andnnl.fileanalysis;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

class ExcelListener extends AnalysisEventListener<List<String>> {
    private static final Logger logger = LoggerFactory.getLogger(ExcelListener.class);
    private FileAnalysis analysis;
    private AnalysisListenerBase listener;
    private AnalysisParam param;
    private int rowCount = 0;
    private int headRowCount = 0;

    public ExcelListener(FileAnalysis analysis, AnalysisListenerBase listener, AnalysisParam param) {
        this.analysis = analysis;
        this.listener = listener;
        this.param = param;
    }

    @Override
    public void invoke(List<String> list, AnalysisContext context) {
        if (null == list) return;
        Integer row = context.readRowHolder().getRowIndex()+1;//行号，从1开始
        if (param.getDelHeadRows() > param.getHeadRowCount()) {
            param.getHeadRowCountAndAdd();
            logger.info("ignore head:" + list);
            analysis.handleHead(list,row, listener, param);
            return;
        }
        rowCount++;
        analysis.handleRow(list,row, listener, param);
        if (!(param.getMaxRow() == 0 || rowCount < param.getMaxRow())) {
            context.interrupt();//读够行数了就停止读取
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        analysis.finish(listener, param);
        listener.finish();
    }


}
